#include "LevelButton.h"
#include "Scene\GameScene\GameScene.h"

LevelButton* LevelButton::createButton(int level) {
	LevelButton *button = new LevelButton();
	if (button && button->initButton(level)) {
		button->autorelease();
		return button;
	}
	CC_SAFE_DELETE(button);
	return button;
}

bool LevelButton::initButton(int level) {
	m_level = level;
	m_isLocked = true;
	m_showSprite = Sprite::create(LEVELBUTTON_BG_NAME);
	m_showSprite->setScale(0.7f);
	this->addChild(m_showSprite);
	auto lock = Sprite::create(LEVELLOCKED_NAME);
	lock->setName("lock");
	this->addChild(lock);

	auto listener = EventListenerTouchOneByOne::create();
	listener->onTouchBegan = CC_CALLBACK_2(LevelButton::onTouchBegan, this);
	listener->onTouchMoved = CC_CALLBACK_2(LevelButton::onTouchMoved, this);
	listener->onTouchEnded = CC_CALLBACK_2(LevelButton::onTouchEnded, this);

	DIRECTOR->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);

	return true;
}

bool LevelButton::isTouchedInside(Touch *pTouch) {
	Vec2 touchPos = pTouch->getLocation();
	Vec2 nodePos = this->convertToNodeSpace(touchPos);
	if (Rect(-m_showSprite->getContentSize().width * 0.5, -m_showSprite->getContentSize().height * 0.5, m_showSprite->getContentSize().width, m_showSprite->getContentSize().height).containsPoint(nodePos)) {
		return true;
	}
	return false;
}

void LevelButton::unLock() {
	auto levelNumber = Label::create(Value(m_level).asString(), TEXTFONT_NAME, 36);
	levelNumber->setColor(Color3B::YELLOW);
	m_isLocked = false;
	this->removeChildByName("lock");
	this->addChild(levelNumber);
}

bool LevelButton::onTouchBegan(Touch *pTouch, Event *event) {
	if (this->isTouchedInside(pTouch)) {
		auto effect = Sprite::create(TOUCHEDEFFECT_NAME);
		effect->setName("touch_effect");
		this->addChild(effect);
		return true;
	}
	else {
		return false;
	}
}

void LevelButton::onTouchMoved(Touch *pTouch, Event *event) {
	if (!this->isTouchedInside(pTouch)) {
		this->removeChildByName("touch_effect");
	}
}

void LevelButton::onTouchEnded(Touch *pTouch, Event *event) {
	if (this->isTouchedInside(pTouch) && !m_isLocked) {
		this->removeChildByName("touch_effect");
		AUDIOENGINE->playEffect(CLICKEFFECT_NAME);
		DIRECTOR->replaceScene(GameScene::createScene(m_level));
	}
	else if (this->isTouchedInside(pTouch) && m_isLocked) {
		this->removeChildByName("touch_effect");
		AUDIOENGINE->playEffect(GOLDOVER_EFFECT_NAME);
	}
}